package com.vlong.town.controller.admin.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vlong.town.controller.base.BaseController;
import com.vlong.town.entity.base.DataMessage;
import com.vlong.town.entity.base.TreeData;
import com.vlong.town.entity.role.Role;
import com.vlong.town.entity.user.User;
import com.vlong.town.entity.userRoleRef.UserRoleRef;
import com.vlong.town.service.role.RoleService;
import com.vlong.town.service.user.UserService;
import com.vlong.town.service.userRoleRef.UserRoleRefService;
import com.vlong.town.util.common.TownConstant;
import com.vlong.town.util.data.DataUtil;
import com.vlong.town.util.pagination.PageTag;

/**
 * 用户管理Controller
 * @author Assassin
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    // Fields

    @Autowired
    private UserService userService;// 用户业务实现类
    @Autowired
    private RoleService roleService;//角色业务实现类
    @Autowired
    private UserRoleRefService userRoleRefService;

    /**
     * 进入用户列表页面
     * @param pageNo 当前页码
     * @param pageSize 每页记录数
     * @return user/list_user
     */
    @RequestMapping("/list")
    public String gotoUserListPage(
            @RequestParam(required=false, value="pageNo") Integer pageNo,
            @RequestParam(required=false, value="pageSize") Integer pageSize,
            @RequestParam(required=false, value="realName") String realName,
            @RequestParam(required=false, value="telphone") String telphone) {
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageHelper.orderBy("update_time DESC");
        List<User> userList = this.userService.queryList(null, 1, 1, 1L, null, null, realName, telphone, null, null, null, null, null);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        PageTag<User> pt = new PageTag<User>(request, "list", pageInfo);
        request.setAttribute("pageHtml", pt.getPageHtml());
        request.setAttribute("realName", realName);
        request.setAttribute("telphone", telphone);
        request.setAttribute("userList", userList);
        return "admin/user/list_user";
    }

    /**
     * 进入用户添加页面
     * @return user/add_user
     */
    @GetMapping("/addUser")
    public String gotoUserAddPage() {
    	List<Role> roleList = roleService.queryList(null, null, 1, getOrgId(), 1, TownConstant.DEL_FLAG_0, null, null, null, null, null);
    	List<TreeData> treeDataList = new ArrayList<TreeData>();
		treeDataList.add(new TreeData("0", null, "用户角色[选择用户所属角色]", false, true));
		for (Role role : roleList) {
			treeDataList.add(new TreeData(role.getRoleId().toString(), "0", role.getRoleName() + "[" + (role.getRoleDesc() == null || "".equals(role.getRoleDesc().trim()) ? "—"  : role.getRoleDesc()) + "]", false, true));
		}
		request.setAttribute("treeData",JSONArray.toJSONString(treeDataList));
        return "admin/user/add_user";
    }

    /**
     * 添加用户
     * @param realName 用户姓名
     * @param telphone 手机号码
     * @param email 电子邮箱
     * @param password 登录密码
     * @return DataMessage->Json
     */
    @ResponseBody
    @PostMapping("executeAddUser")
    public DataMessage addUser(
            @RequestParam(name="realName", required=true) String realName,
            @RequestParam(name="telphone", required=true) String telphone,
            @RequestParam(name="password", required=true) String password,
            @RequestParam(name="email", required=false) String email,
            @RequestParam(name="roleIds", required=false) String roleIds
    		) {
        DataMessage dm = new DataMessage();
        // 后台验证
        if(!this.validateStringProperty(realName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户姓名不合法");
            return dm;
        }
        if(!this.validateStringProperty(telphone, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("手机号码不合法");
            return dm;
        }
        if(!this.validateStringProperty(password, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("登录密码不合法");
            return dm;
        }
        if(!this.validateStringProperty(roleIds, 2, 128)) {
			dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
			dm.setMessage("用户角色参数错误");
			return  dm;
		} 
        int status = 1;// 默认用户状态可用
        int type = 1;// 1-用户
        Long cuTime = System.currentTimeMillis();// 添加时间
        this.userService.add(null, status, type, getOrgId(), null, null, realName, telphone, email, DataUtil.generateMD5(password.getBytes()), null,null, cuTime, cuTime,roleIds);
        dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
        dm.setMessage("用户添加成功");
        return dm;
    }

    /**
     * 进入用户编辑页面
     * @param userId 主键值
     * @return user/edit_user
     */
    @GetMapping(value = "/editUser/{userId}")
    public String gotoUserEditPage(@PathVariable(required=true, value="userId") Long userId) {
    	//查询角色
    	List<UserRoleRef> refList = this.userRoleRefService.queryList(userId);
    	List<Role> roleList = roleService.queryList(null, null, 1, getOrgId(), 1, TownConstant.DEL_FLAG_0, null, null, null, null, null);
    	List<TreeData> treeDataList = new ArrayList<TreeData>();
		treeDataList.add(new TreeData("0", null, "用户角色[选择用户所属角色]", false, true));
		for (Role role : roleList) {
			boolean isChecked = false;
			for(UserRoleRef ref : refList) {
				if(role.getRoleId().longValue() == ref.getRoleId().longValue()) {
					isChecked = true;
					break;
				}
			}
			treeDataList.add(new TreeData(role.getRoleId().toString(), "0",role.getRoleName() + "[" + (role.getRoleDesc() == null || "".equals(role.getRoleDesc().trim())? "—" : role.getRoleDesc()) + "]",isChecked, true));
		}
		request.setAttribute("treeData",JSONArray.toJSONString(treeDataList));
    	
		//查询用户
    	User user = this.userService.queryById(userId);
        request.setAttribute("user", user);
        return "admin/user/edit_user";
    }

    /**
     * 编辑用户
     * @param userId 用户Id
     * @param realName 专家姓名
     * @param telphone 手机号码
     * @param email 电子邮箱
     * @return DataMessage->Json
     */
    @ResponseBody
    @PostMapping("/executeEditUser")
    public DataMessage editUser(
            @RequestParam(name="userId", required=true) Long userId,
            @RequestParam(name="realName", required=true) String realName,
            @RequestParam(name="telphone", required=true) String telphone,
            @RequestParam(name="email", required=false) String email,
            @RequestParam(name="roleIds", required=false) String roleIds
    		) {
        DataMessage dm = new DataMessage();
        // 后台验证
        if(!this.validateStringProperty(realName, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户姓名不合法");
            return dm;
        }
        if(!this.validateStringProperty(telphone, 1, 50)) {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("手机号码不合法");
            return dm;
        }
        this.userService.edit(userId, null, null, getOrgId(), null, null, realName, telphone, email, null, null, null, null, System.currentTimeMillis(),roleIds);
        dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
        dm.setMessage("用户编辑成功");
        return dm;
    }

    /**
     * 删除用户
     * @param userId 主键值
     * @return DataMessage->Json
     */
    @ResponseBody
    @PostMapping("/delete")
    public DataMessage deleteUser(@RequestParam(required=true, value="userId") Long userId) {
        DataMessage dm = new DataMessage();
        if(userId != null && userId > 0L) {
            this.userService.edit(userId, 2, null, null, null, null, null, null, null, null, null, null, null, System.currentTimeMillis(),null);
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }

    /**
     * 批量删除用户
     * @param userIds 主键值集合字符串
     * @return DataMessage->Json
     */
    @ResponseBody
    @PostMapping("/batchDelete")
    public DataMessage batchDeleteUser(@RequestParam(required=true, value="userIds") String userIds) {
        DataMessage dm = new DataMessage();
        if(this.validateStringProperty(userIds, 1, 128)) {
            String[] userIdArray = userIds.split(",");
            for(String userId : userIdArray) {
                this.userService.edit(Long.parseLong(userId), 2, null, null, null, null, null, null, null, null, null, null, null, System.currentTimeMillis(),null);
            }
            dm.setResult(TownConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户删除成功");
        } else {
            dm.setResult(TownConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("参数错误");
        }
        return dm;
    }

}
